package edu.fhsu.csci468;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.Socket;

import javax.swing.event.EventListenerList;

public class Sensor implements Runnable
{
	private EventListenerList listenerList = new EventListenerList();

	private Socket incoming;
	private ObjectInputStream inStream;
	
	private int sensorID;
	private SensorType sensorType;
	
	public int getSensorID()
	{
		return sensorID;
	}

	public SensorType getSensorType()
	{
		return sensorType;
	}
	
	public Sensor(Socket incoming, int id)
	{
		this.incoming = incoming;
		this.sensorID = id;
		
		getStreams();

		// Get Sensor type
		try
		{
			try
			{
				sensorType = (SensorType) inStream.readObject();
			} catch (ClassNotFoundException classNotFoundException)
			{
				System.out.println(classNotFoundException.getCause());
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}

	}

	public void getStreams()
	{
		try
		{
			try
			{
				inStream = new ObjectInputStream(new BufferedInputStream(
						incoming.getInputStream()));
			} finally
			{
				// incoming.close();
			}
		} catch (IOException e)
		{
			e.printStackTrace();
		}
	}

	public void run()
	{
		// listen to the socket for the event to happen
		SensorAction receive = SensorAction.Discontect;
		do
		{
			try
			{
				receive = (SensorAction) inStream.readObject();
			} catch (ClassNotFoundException classNotFoundException)
			{
				System.out.println(classNotFoundException.getCause());
			} catch (IOException e)
			{
				// // Need to say the sensor is offline

				e.printStackTrace();
			}
			finally
			{
			// action happened send packet off
			// // need to make SensorEvent that has meaning
			fireSensorEvent(new SensorEvent(this, sensorID, receive));
			}
		} while (receive != SensorAction.Discontect);
	}

	public void addSensorEventListener(ISensorEventListener eventListener)
	{
		listenerList.add(ISensorEventListener.class, eventListener);
	}

	public void removeSensorEventListener(ISensorEventListener eventListener)
	{
		listenerList.remove(ISensorEventListener.class, eventListener);
	}

	public void removeAllSensorEventListeners()
	{
		listenerList = new EventListenerList();
	}

	private void fireSensorEvent(SensorEvent event)
	{
		Object[] listeners = listenerList.getListenerList();
		// Each listener occupies two elements - the first is the listener class
		// and the second is the listener instance
		for (int i = 0; i < listeners.length; i += 2)
		{
			if (listeners[i] == ISensorEventListener.class)
			{
				((ISensorEventListener) listeners[i + 1])
						.sensorEventOccurred(event);
			}
		}
	}

}
